import { defineStore } from "pinia";
import mqtt from "mqtt";
import useLightStore from "./light";

// 把时间字符串解析成Date, 如183000 -> 18:30:00
function parseTimeStrToDate(timeStr) {
  // 检查输入字符串长度是否符合要求
  // if (timeStr.length !== 6) {
  //   throw new Error("输入的字符串长度必须为6位");
  // }
  const hours = parseInt(timeStr.slice(0, 2), 10);
  const minutes = parseInt(timeStr.slice(2, 4), 10);
  const seconds = parseInt(timeStr.slice(4, 6), 10);

  // 创建一个当前日期的 Date 对象
  const currentDate = new Date();

  // 设置时分秒
  currentDate.setHours(hours, minutes, seconds, 0);

  return currentDate;
}


export default defineStore("mqtt", {
  state() {
    return {
      client: null,
      connected: false,
      connectionInfo: {
        protocol: "ws",
        host: import.meta.env.VITE_MQTT_HOST,
        port: import.meta.env.VITE_MQTT_PORT,
        clientId: import.meta.env.VITE_MQTT_CLIENT_ID + Math.random().toString(16).substring(2, 8),
        username: "",
        password: ""
      },
      subTopic: import.meta.env.VITE_MQTT_SUB_TOPIC,
      pubTopic: import.meta.env.VITE_MQTT_PUB_TOPIC
    };
  },
  actions: {
    // 设置用户名密码
    setUsernamePassword(username, password) {
      this.connectionInfo.username = username;
      this.connectionInfo.password = password;
    },
    // 连接MQTT服务器
    connect() {
      if (this.connected) {
        ElMessage("已连接");
        console.log("已连接");
        return;
      }
      const { protocol, host, port, ...options } = this.connectionInfo;
      if (options.username === "" || options.password === "") {
        ElMessage({
          message: "未设置用户名密码",
          type: "warning",
          showClose: true
        });
        console.log("未设置用户名或密码");
        return;
      }
      const url = `${protocol}://${host}:${port}/mqtt`;

      try {
        this.client = mqtt.connect(url, options);
        const lightStore = useLightStore();

        if (this.client.on) {
          this.client.on("connect", () => {
            this.connected = true;
            console.log("连接成功");
            ElMessage({
              message: "连接成功",
              type: "success",
              showClose: true
            });

            this.subscribe();
          });
          this.client.on("reconnect", () => {
            try {
              this.client.end();
            } catch (error) {
              console.log(error);
            }
          });
          this.client.on("error", (error) => {
            console.log("连接失败: ", error);
            ElMessage({
              message: "连接失败",
              type: "error",
              showClose: true
            });
          });
          this.client.on("message", (topic, payload) => {
            console.log(`接收到消息 ${payload} 来自 topic ${topic}`);

            let parts = topic.split("/"); // 按照 "/" 分割topic
            let lastPart = parts[parts.length - 1]; // 获取数组的最后一个元素

            switch (lastPart) {
              case "brightness":
                lightStore.setBrightness(parseInt(payload, 10));
                break;
              case "mode":
                lightStore.setMode(parseInt(payload, 10));
                break;
              case "time_range":
                const arr = String(payload).split(";");
                if (arr.length != 2) break;
                const start = parseTimeStrToDate(arr[0]);
                const end = parseTimeStrToDate(arr[1]);
                lightStore.setTimeRange(start, end);
                break;
              default:
                break;
            }
          });
        }
      } catch (error) {
        console.log("连接失败: ", error);
      }
    },
    // 断开连接MQTT服务器
    disconnect() {
      if (!this.connected) {
        ElMessage("已断开连接");
        console.log("已断开连接");
        return;
      }
      this.client.end(false, () => {
        this.connected = false;
        console.log("连接断开");
        ElMessage({
          message: "连接断开",
          type: "success",
          showClose: true
        });
      });
    },
    // 订阅消息
    subscribe() {
      this.client.subscribe(this.subTopic, { qos: 0 }, (error, res) => {
        if (error) {
          console.log("订阅失败", error);
          return;
        }
        console.log("订阅成功", res);
      });
    },
    // 发布消息
    publish(path, payload, qos) {
      const topic = this.pubTopic + path;
      this.client.publish(topic, payload, { qos }, (error) => {
        console.log(`发布消息 ${payload} 到 ${topic}`);

        if (error) {
          console.log("发布消息失败", error);
        }
      });
    }
  }
});
